// page/recommendSong/recommendSong.js
import pubsub from 'pubsub-js';
import request from '../../../utils/request.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    day: '',
    month: '',
    recommendList: [],
    index: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //动态获取日期
    this.setData({
      day: new Date().getDate(),
      month: new Date().getMonth() + 1
    })
    this.getRecommendList()
    //订阅songDetail发布的type消息
    pubsub.subscribe('switchType', (msg, switchType) => {
      let { recommendList, index } = this.data
      // console.log('来自songDetail发布的消息',msg,data);
      if (switchType === "pre") {//上一首
        //设置边界
        if (index === 0) {
          index = recommendList.length
        }
        //临界值判断也可以写成 (index === 0) && (index = recommendList.length);
        index -= 1
      } else {//下一首
        //设置边界
        if (index = recommendList.length) {
          index = -1
        }
        //临界值判断也可以写成 (index === recommendList.length -1) && (index = -1)
        index += 1
      }
      let musicId = recommendList[index].id
      //更新一下index 要不都是同一个值
      this.setData({
        index
      })
      //将最新的musicId发送给songDetail
      pubsub.publish('musicId', musicId)
    })
  },
  //获取每日推荐recommendList的数据
  async getRecommendList() {
    let result = await request('/recommend/songs')
    //console.log(result);
    this.setData({
      recommendList: result.recommend
    })

  },
  //跳转到songDetail详情页
  toSongDetail(event) {
    console.log(event);
    //let song = event.currentTarget.dataset.song
    //let musicId = event.currentTarget.dataset.id
    let { song, musicid, index } = event.currentTarget.dataset
    //console.log(song);
    //路由传参 query  {song:"[object,object]"}时需要  JSON.stringify(song)
    //更新点击的音乐的下标
    this.setData({
      index
    })
    wx.navigateTo({
      url: '/songPackage/pages/songDetail/songDetail?musicId=' + musicid
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})